import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Scanner;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.ThreadPoolExecutor;

/**
 * @author 徐志荣
 * @date 2023/4/7 10:54
 */
public class TcpEchoServer {
    private ServerSocket serverSocket = null;

    public TcpEchoServer(int port) throws IOException {
        serverSocket = new ServerSocket(port);
    }

    public void start() throws IOException {
        ExecutorService executorService = Executors.newCachedThreadPool();

        System.out.println("服务器启动!");
        while(true){
            Socket clientSocket = serverSocket.accept();
            //如果直接调用,该方法会影响这个循环的二次执行,导致accept不及时了
            //创建线程
       /*     Thread thread = new Thread(()->{
                try {
                    processConnection(clientSocket);
                } catch (IOException e) {
                    e.printStackTrace();
                }

            });
            thread.start();
            */
            executorService.submit(new Runnable() {
                @Override
                public void run() {
                    try {
                        processConnection(clientSocket);
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            });

        }
    }

    //通过这个方法来处理一个连接
    //读取请求
    //根据请求计算响应
    //把响应返回给客户端
    private void processConnection(Socket clientSocket) throws IOException {
        System.out.printf("[%s : %d] 客户端上线\n",clientSocket.getInetAddress().toString(),
                clientSocket.getPort());
        //try()  这种写法,()中允许创建多个刘对象, 使用 ; 来分割
        try(InputStream inputStream = clientSocket.getInputStream();
            OutputStream outputStream = clientSocket.getOutputStream()){
            //scanner 是相当于字符流,上述约定了请求是字符串,所以就可以使用字符流来处理
            Scanner scanner = new Scanner(inputStream);
            PrintWriter printWriter = new PrintWriter(outputStream);
            while (true){
                //1. 读取请求
                if(!scanner.hasNext()){
                    //读取的流到了结尾了(对端关闭了)
                    System.out.printf("[%s : %d] 客户端下线\n",clientSocket.getInetAddress().toString(),
                            clientSocket.getPort());
                    break;
                }
                //客户端关闭连接,此时hasNext会返回false,循环结束
                //如果对端有数据,hasNext返回true
                //直接使用 scanner 读取一段字符串 ,读到 空白符为止
                String request = scanner.next();
                //2. 根据请求计算响应
                String response = process(request);
                //3. 把响应写回给客户端, 输出也得带上换行
                printWriter.println(response);
                printWriter.flush();
                System.out.printf("[%s:%d] req:%s;resp:%s\n",clientSocket.getInetAddress().toString(),
                        clientSocket.getPort(),request,response);
            }
        }catch (IOException e){
            e.printStackTrace();
        }finally {
            clientSocket.close();
        }
    }

    private String process(String request) {
        return  request;
    }

    public static void main(String[] args) throws IOException {
        TcpEchoServer tcpEchoServer = new TcpEchoServer(9090);
        tcpEchoServer.start();
    }
}
